package com.sservice.web.controller.admin;

import com.sservice.common.CompareObject;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.*;
import com.sservice.model.vo.PurchaseOrderBillLogVo;
import com.sservice.model.vo.PurchaseOrderBillVo;
import com.sservice.urp.dao.IComDao;
import com.sservice.urp.entity.Com;
import com.sservice.urp.entity.Permission;
import com.sservice.urp.entity.User;
import com.sservice.urp.vo.UserVo;
import com.sservice.service.service.*;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.web.utils.PdfUtils;
import com.lowagie.text.DocumentException;
import com.sservice.web.common.Utils;
import com.sservice.model.entity.*;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/purchaseOrderBill/")
public class PurchaseOrderBillController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PurchaseOrderBillService service;
    @Autowired
    private PurchaseOrderBillMapper mapper;
    @Autowired
    private OrderPaperMapper orderPaperMapper;
    @Autowired
    private PurchaseOrderService poService;
    @Autowired
    private IClienteleDao clienteleDao;
    @Autowired
    private ILadingBillDao lbDao;
    @Autowired
    private IOrderPaperService orderPaperService;
    @Autowired
    private LadingOrderMapper loDao;
    @Autowired
    private IStoreDao storeDao;
    @Autowired
    private IComDao comDao;
    @Autowired
    private IGoodsDao goodsDao;
    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private PurchaseOrderBillLogService serviceLog;
    @Autowired
    private IPermissionService iPermissionService;

    @Autowired
    private ExportService exportService;
    final static String Date1970 = "1970-01-01";


    public Map getFieldValue() {
        Map map = new HashMap();
        map.put("numberReceive", "入库数量");
        map.put("remark", "备注");
        return map;
    }

    public String toString(Object obj) {
        List<String> strArr = new ArrayList<String>();
        Map map = (Map) obj;
        for (Object str : map.keySet()) {
            strArr.add(getFieldValue().get(str).toString() + map.get(str));
        }
        return StringUtils.join(strArr, ",");
    }

    public void log(Object content, HttpServletRequest request, Integer purchaseId) {
        PurchaseOrderBillLog log = new PurchaseOrderBillLog();
        if (content instanceof Map) {
            log.setContent(toString(content));
        } else {
            log.setContent(content.toString());
        }
        if (log.getContent().length() == 0) {
            return;
        }
        log.setOrderBillId(purchaseId.toString());
        User user = (User) request.getSession().getAttribute(Constants.USER);
        log.setUserId(String.valueOf(user.getId()));
        log.setIp(Constants.getIP(request));
        serviceLog.insertSelective(log);
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(PurchaseOrderBillVo arg, HttpSession session) {
        List<PurchaseOrderBillVo> list_order = service.queryByPage(arg);
        int total = service.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detailList", method = RequestMethod.GET)
    public ListResult detailList(PurchaseOrderBillVo arg) {
        return new ListResult(true, mapper.queryDetailByNo(arg));
    }

    /***
     * 查询发票
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPaper", method = RequestMethod.GET)
    public ListResult queryPaper(PurchaseOrderBillVo arg, HttpSession session, boolean isExport) {
        List<PurchaseOrderBillVo> list_order = mapper.queryPaperByPage(arg);
        if (isExport) return new ListResult(true, list_order);
        int total = service.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    /**
     * 导出未收票金额
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exportPaper", method = RequestMethod.GET)
    public OutputStream exportPaper(PurchaseOrderBillVo arg, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        arg.setPage(0);
        arg.setSize(Integer.MAX_VALUE);// max value
        ListResult list1 = queryPaper(arg, session, true);
        List<PurchaseOrderBillVo> list = (List<PurchaseOrderBillVo>) list1.getList();
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "待收发票明细Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "发票"; // sheet 名称
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            PurchaseOrderBillVo ov = list.get(i);
            map.put("供应商", ov.getClienteleName());
            map.put("收货单号", ov.getNo());
            map.put("产品", ov.getGoodsName());
            map.put("单价", ov.getPrice());
            map.put("实提数量", ov.getNumberReceive());
            map.put("已收票数量", ov.getNumberPapered());
            map.put("收货单状态",
                    "0".equals(ov.getStatus()) ? "未执行" : (
                            "1".equals(ov.getStatus()) ? "执行中" : "执行完毕"));
            map.put("发票状态", ov.getNumberPapered() == null ? "未收票" :
                    (BigDecimal.ZERO.compareTo(ov.getNumberPapered()) == 0 ? "未ov.getNumberPapered()票" : (
                            ov.getNumberPapered().compareTo(BigDecimal.ZERO) == 1 && ov.getNumberPapered().compareTo(ov.getNumberReceive()) == -1 ? "部分收票" : "完全收票"
                    ))
            );
            map.put("审核状态", "0".equals(ov.getCheckStatus()) ? "未审核" : ("1".equals(ov.getCheckStatus()) ? "通过" : "未通过"));
            map.put("申请用户", ov.getUserName());
            map.put("申请时间", ov.getPaperApplyTime() == null ? "" : sdf1.format(ov.getPaperApplyTime()));

            BigDecimal total = ov.getPrice().multiply(ov.getNumber());
            BigDecimal taxTotal = Utils.taxTotal(ov.getTaxRatio(), total);
            map.put("税率", ov.getTaxRatio());
            map.put("不含税金额", total.subtract(taxTotal));
            map.put("税额", taxTotal);
            map.put("价税合计金额", total);
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }

    @ResponseBody
    @RequestMapping(value = "/queryWithAuth", method = RequestMethod.GET)
    public ListResult queryWithAuth(PurchaseOrderBillVo arg, HttpSession session, boolean isExport) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            List<String> lstr = iGoodsService.judgeOperator(user.getId());
            if (!isManger && 0 == lstr.size()) {
                return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
            } else {
                arg.setList(lstr);
            }
        }
        if (isExport) {
            arg.setPage(0);
            arg.setSize(Integer.MAX_VALUE);
            List<PurchaseOrderBillVo> list_order = service.queryByPage(arg);
            return new ListResult(true, list_order);
        }

        List<PurchaseOrderBillVo> list_order = service.queryByPage(arg);
        int total = service.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryCanSell", method = RequestMethod.GET)
    public ListResult queryCanSell(PurchaseOrderBillVo arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            List<String> lstr = iGoodsService.judgeOperator(user.getId());
            if (!isManger && 0 == lstr.size()) {
                return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
            }
            arg.setList(lstr);
        }
        List<PurchaseOrderBillVo> list_order = mapper.queryCanSellUnion(arg);


        return new ListResult(true, list_order);
    }

    /***
     * 可卖货数量 导出
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @RequestMapping(value = "/exportCanSell", method = RequestMethod.GET)
    public OutputStream exportCanSell(PurchaseOrderBillVo arg, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            List<String> lstr = iGoodsService.judgeOperator(user.getId());
            if (!isManger && 0 == lstr.size()) {
                return null; // (false, "非运营或超级管理员角色账号，无权访问!", 403);
            }
            arg.setList(lstr);
        }
        List<PurchaseOrderBillVo> list = mapper.queryCanSellUnion(arg);
        BigDecimal preTotal = BigDecimal.valueOf(0.0);
        BigDecimal preSell = BigDecimal.valueOf(0.0);
        BigDecimal actualSell = BigDecimal.valueOf(0.0);
        BigDecimal actualBuy = BigDecimal.valueOf(0.0);
        BigDecimal buyInRoad = BigDecimal.valueOf(0.0);
        BigDecimal canSell = BigDecimal.valueOf(0.0);
        arg.setMonthEnd(Utils.getYesterdayDate(arg.getMonthStart()));
        arg.setMonthStart(Date1970);
        List<PurchaseOrderBillVo> listPre = mapper.queryCanSellUnion(arg);
        Map<String, Object> listMap = Utils.convertListToMap(list, PurchaseOrderBill.class, "goodsNo,quality,storeName");

        Map<String, Object> listMapPre = Utils.convertListToMap(listPre, PurchaseOrderBill.class, "goodsNo,quality,storeName");
        for (PurchaseOrderBillVo pbv : listPre) {
            if (listMap.get(pbv.getGoodsNo() + pbv.getQuality() + pbv.getStoreName()) == null) {
                PurchaseOrderBillVo pb = new PurchaseOrderBillVo();
                pb.setGoodsName(pbv.getGoodsName());
                pb.setGoodsNo(pbv.getGoodsNo());
                pb.setQuality(pbv.getQuality());
                pb.setStoreName(pbv.getStoreName());
                list.add(initNumber(pb));
            }
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        exportService.setResponseHeader(response, request, "可卖货数量Excel");
        String hql = "可卖货数量";
        List<Map> lm = new ArrayList<Map>();

        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            PurchaseOrderBillVo ov = list.get(i);
            map.put("产品名称", ov.getGoodsName());
            map.put("产品编码", ov.getGoodsNo());
            Object obj = listMapPre.get(ov.getGoodsNo() + ov.getQuality() + ov.getStoreName());
            PurchaseOrderBillVo ovPre = null;
            BigDecimal preTotal_ = BigDecimal.valueOf(0.0);
            if (obj != null) {
                ovPre = (PurchaseOrderBillVo) obj;
                preTotal_ = preTotal_.add(getCanSell(ovPre));
            }
            preTotal = preTotal.add(preTotal_);
            preSell = preSell.add(BigDecimal.valueOf(ov.getNumberPreSell()));
            actualSell = preSell.add(ov.getNumberSended() != null ? ov.getNumberSended() : BigDecimal.ZERO);
            actualBuy = actualBuy.add(BigDecimal.valueOf(ov.getNumberActualBuy()));
            buyInRoad = buyInRoad.add(BigDecimal.valueOf(ov.getNumberInRoad()));
            canSell = canSell.add(preTotal.add(getCanSell(ov)));
            map.put("上期结转", preTotal_);
            map.put("库区", ov.getStoreName());
            map.put("品质规格", ov.getQuality());
            map.put("预定销售数量", ov.getNumberPreSell());
            map.put("实际销售数量", ov.getNumberSended());
            map.put("实际采购数量", ov.getNumberActualBuy());
            map.put("采购在途数量", ov.getNumberInRoad());
            map.put("可卖货数量", preTotal.add(getCanSell(ov)));
            lm.add(map);
        }

        // 合计
        Map map = new LinkedHashMap();
        map.put("产品名称", "合计");
        map.put("产品编码", null);
        map.put("上期结转", preTotal);
        map.put("库区", null);
        map.put("品质规格", null);
        map.put("预定销售数量", preSell);
        map.put("实际销售数量", actualSell);
        map.put("实际采购数量", actualBuy);
        map.put("采购在途数量", buyInRoad);
        map.put("可卖货数量", canSell);
        lm.add(map);
        return exportService.exportExcel(hql, lm, outputStream);
    }

    public PurchaseOrderBillVo initNumber(PurchaseOrderBillVo ov) {
        ov.setNumberPreSell(0.0);
        ov.setNumberSended(BigDecimal.valueOf(0.0));
        ov.setNumberActualBuy(0.0);
        ov.setNumberInRoad((0.0));
        ov.setNumberSending(BigDecimal.valueOf(0.0));
        ov.setNumberReceiving(0.0);
        ov.setNumberSended(BigDecimal.valueOf(0.0));
        ov.setNumberReceive(BigDecimal.valueOf(0.0));
        return ov;
    }

    public BigDecimal getCanSell(PurchaseOrderBillVo ovPre) {
        return BigDecimal.valueOf(ovPre.getNumberActualBuy())
                .add(BigDecimal.valueOf(ovPre.getNumberInRoad()))
                .subtract(BigDecimal.valueOf(ovPre.getNumberPreSell()))
                .subtract(BigDecimal.valueOf(ovPre.getNumberActualSell()));
    }


    @ResponseBody
    @RequestMapping(value = "/queryCanSend", method = RequestMethod.GET)
    public ListResult queryCanSend(PurchaseOrderBillVo arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            Goods g = new Goods();
            g.setOperatorId(String.valueOf(user.getId()));
            List<Goods> list = goodsDao.queryFindInSet(g);
            if (!isManger && 0 == list.size()) {
                return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
            }
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }
        List<PurchaseOrderBillVo> list_order = mapper.queryCanSend(arg);
        return new ListResult(true, list_order);
    }

    /**
     * 可发货数量导出
     *
     * @param arg
     * @param session
     * @return
     */
    @RequestMapping(value = "/exportCanSend", method = RequestMethod.GET)
    public OutputStream exportCanSend(PurchaseOrderBillVo arg, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            Goods g = new Goods();
            g.setOperatorId(String.valueOf(user.getId()));
            List<Goods> list = goodsDao.queryFindInSet(g);
            if (!isManger && 0 == list.size()) {
                return null;
            }
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }
        List<PurchaseOrderBillVo> list = mapper.queryCanSend(arg);
        BigDecimal preTotal = BigDecimal.valueOf(0.0);
        BigDecimal preSending = BigDecimal.valueOf(0.0);
        BigDecimal actualExist = BigDecimal.valueOf(0.0);
        BigDecimal receiving = BigDecimal.valueOf(0.0);
        BigDecimal canSend = BigDecimal.valueOf(0.0);
        arg.setMonthEnd(Utils.getYesterdayDate(arg.getMonthStart()));
        arg.setMonthStart(Date1970);
        List<PurchaseOrderBillVo> listPre = mapper.queryCanSend(arg);
        Map<String, Object> listMap = Utils.convertListToMap(list, PurchaseOrderBill.class, "goodsNo,quality,storeName");
        Map<String, Object> listMapPre = Utils.convertListToMap(listPre, PurchaseOrderBill.class, "goodsNo,quality,storeName");
        for (PurchaseOrderBillVo pbv : listPre) {
            if (listMap.get(pbv.getGoodsNo() + pbv.getQuality() + pbv.getStoreName()) == null) {
                PurchaseOrderBillVo pb = new PurchaseOrderBillVo();
                pb.setGoodsName(pbv.getGoodsName());
                pb.setGoodsNo(pbv.getGoodsNo());
                pb.setQuality(pbv.getQuality());
                pb.setStoreName(pbv.getStoreName());
                list.add(initNumber(pb));
            }
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        exportService.setResponseHeader(response, request, "可发货数量Excel");
        String hql = "可发货数量";
        List<Map> lm = new ArrayList<Map>();

        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            PurchaseOrderBillVo ov = list.get(i);
            map.put("产品名称", ov.getGoodsName());
            map.put("产品编码", ov.getGoodsNo());
            Object obj = listMapPre.get(ov.getGoodsNo() + ov.getQuality() + ov.getStoreName());
            PurchaseOrderBillVo ovPre = null;
            BigDecimal preTotal_ = BigDecimal.valueOf(0.0);
            if (obj != null) {
                ovPre = (PurchaseOrderBillVo) obj;
                preTotal_ = preTotal_.add(getCanSend(ovPre));
            }
            preTotal = preTotal.add(preTotal_);
            preSending = preSending.add(ov.getNumberSending());
            actualExist = actualExist.add(ov.getNumberReceive());
            receiving = receiving.add(BigDecimal.valueOf(ov.getNumberReceiving()));
            canSend = canSend.add(getCanSend(ov).add(preTotal_));
            map.put("上期结转", preTotal_);
            map.put("库区", ov.getStoreName());
            map.put("品质规格", ov.getQuality());
            map.put("发货中数量", ov.getNumberSending());
            map.put("实际库存数量", ov.getNumberReceive());
            map.put("收货中数量", ov.getNumberReceiving());
            map.put("可发货数量", getCanSend(ov).add(preTotal_));
            lm.add(map);
        }

        // 合计
        Map map = new LinkedHashMap();
        map.put("产品名称", "合计");
        map.put("产品编码", null);
        map.put("上期结转", preTotal);
        map.put("库区", null);
        map.put("品质规格", null);
        map.put("发货中数量", preSending);
        map.put("实际库存数量", actualExist);
        map.put("收货中数量", receiving);
        map.put("可发货数量", canSend);
        lm.add(map);
        return exportService.exportExcel(hql, lm, outputStream);
    }


    /**
     * 某期可发货数量
     *
     * @param ovPre
     * @return
     */
    public BigDecimal getCanSend(PurchaseOrderBillVo ovPre) {
        return ovPre.getNumberReceive()
                .add(BigDecimal.valueOf(ovPre.getNumberReceiving()))
                .subtract(ovPre.getNumberSending());
    }

    @RequestMapping(value = "/{id}-{clientleName}.pdf")
    public OutputStream toPdf(PurchaseOrder order, String id, String clientName, HttpSession session, HttpServletResponse response) throws DocumentException, TemplateException, IOException {
        OrderPaper op = new OrderPaper();
        op.setOrderId(String.valueOf(order.getId()));
        op.setOrderType("3");
        OrderPaper op1 = orderPaperMapper.selectByOrderIdAndOrderType(op);
        ClassPathResource resource = new ClassPathResource("paper/bill.ftl");
        Map<Object, Object> o = new HashMap<Object, Object>();
        String body = new String(op1.getPaper());
        o.put("body", body);
        String path_ = resource.getURL().toString().replace("paper/bill.ftl", "");
        return PdfUtils.generateToServletOutputStream(path_.replace("file:" + (path_.indexOf("usr/") > -1 ? "" : "/"), ""), "paper/bill.ftl",
                resource.getURL().toString().replace("paper/bill.ftl", ""), o, response);
    }

    /***
     * 收货单 打印
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOrderPaper", method = RequestMethod.GET)
    public BaseResult getOrderPaper(OrderPaper op, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (1 == user.getId()) {
            return new BaseResult(false, "超级管理员不能打印合同", 403);
        }
        op.setOrderType("3"); // 收货单
        PurchaseOrderBill pob = service.selectByPrimaryKey(Integer.valueOf(op.getOrderId()));
        OrderPaper pop = orderPaperMapper.selectByOrderIdAndOrderType(op); // 存在隐患
        if ("1".equals(pob.getCheckStatus()) && pop != null) {
            if (pop != null&& pop.getPaper()!= null) {
                pop.setPaper_(new String(pop.getPaper()));
            }
            return new BaseResult(true, pop);
        } else {
            if ("0".equals(pob.getType())) {
                if (pob.getCom() == null) {
                    return new BaseResult(false, "车号类型收货单，请提货回填车号后进行打印收货单!", 403);
                }
            }
            PurchaseOrderBillVo pobv = new PurchaseOrderBillVo();
            pobv.setNo(pob.getNo());
            List<PurchaseOrderBillVo> list = service.queryByPage(pobv);
            for (PurchaseOrderBillVo po : list) {
                if (!po.getId().equals(pob.getId())) {
                    pob.setNumber(po.getNumber().add(pob.getNumber()));
                }
            }
            Clientele clientel = clienteleDao.selectByPrimaryKey(Integer.valueOf(pob.getClienteleId())); //
            Map map = new HashMap();
            if (pop != null) {
                map.put("paper_", new String(pop.getPaper()));
            }
            map.put("no", pob.getNo());
            map.put("com", pob.getCom()); // 车号、收货公司
            map.put("quality", pob.getQuality()); // 质量规格
            map.put("type", pob.getType());
            map.put("number", pob.getNumber());
            map.put("expireTime", pob.getStoreTime());
            map.put("expire", pob.getStoreTime());
            Store store = storeDao.selectByPrimaryKey(Integer.valueOf(pob.getStoreId()));
            map.put("createAt", pob.getCreateAt());
            map.put("storeName", store.getName());
            map.put("paperId", pob.getPaperId());// 销售合同号
            map.put("providerFax", clientel.getFax()); /// 供应商传真
            map.put("shortName", store.getShortName());
            if ("0".equals(pob.getType()) && "1".equals(store.getShowDriver())) {
                LadingOrder lo1 = new LadingOrder();
                lo1.setBillId(String.valueOf(pob.getId()));
                LadingOrder lo = loDao.queryPurchaseBill(lo1);
                if (lo != null) {
                    LadingBill lb = lbDao.selectByPrimaryKey(Integer.valueOf(lo.getLadingId()));
                    map.put("driver", lb.getDriver());
                    map.put("driverPhone", lb.getDriverPhone());
                }
            }
            map.put("userName", user.getName());// 制单人
            Com com = comDao.selectByPrimaryKey(Integer.valueOf(user.getComid()));
            map.put("fax", com.getFax());// 传真
            map.put("tel", com.getTel());// 电话
            return new BaseResult(true, map);
        }
    }

    /**
     * 日志查询
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/log/query", method = RequestMethod.GET)
    public ListResult logQuery(PurchaseOrderBillLogVo arg, HttpSession session) {
        List<PurchaseOrderBillLogVo> list_order = serviceLog.queryByPage(arg);
        int total = serviceLog.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<PurchaseOrderBill> get(PurchaseOrderBillVo arg, HttpSession session) {
        PurchaseOrderBill p = service.selectByPrimaryKey(arg.getId());
        return new BaseResult<PurchaseOrderBill>(true, p);
    }

    @ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ListResult detail(PurchaseOrderBillVo arg, HttpSession session) {
//        PurchaseOrderBillVo p = mapper.detailById(arg.getId());
        List list = mapper.queryByPage(arg);
        return new ListResult(true, list);
    }


    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult create(PurchaseOrderBill arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        Object list_order = service.createBill(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        return new BaseResult(true, list_order.toString());
    }

    /***
     * 采购订单合并收huo
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/receiveCombine", method = RequestMethod.POST)
    public BaseResult receiveCombine(PurchaseOrderBillVo arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        Object list_order = service.createBillByCombineOrder(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        return new BaseResult(true, list_order.toString());
    }

    /**
     * 多个采购订单的收货
     *
     * @param arg
     * @param session
     * @return
     */
//    @SameUrlData
//    @ResponseBody
//    @RequestMapping(value = "/receiveMultiOrder", method = RequestMethod.POST)
//    public BaseResult receiveMultiOrder(PurchaseOrderBill arg, HttpSession session) {
//        User user = (User) session.getAttribute(Constants.USER);
//        arg.setCreateId(String.valueOf(user.getId()));
//        Object list_order = service.multiOrderToBill(arg);
//        if (list_order instanceof String) {
//            return new BaseResult(false, list_order.toString(), 403);
//        }
//        return new BaseResult(true, list_order.toString());
//    }

    /***
     * 实体数清零
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/clear/{id}", method = RequestMethod.GET)
    public BaseResult clear(PurchaseOrderBill arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        Object list_order = service.clear(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        log("清零", request, arg.getId());
        return new BaseResult(true, list_order.toString(), 200);
    }

    /****
     *  订单合并收货 清零
     * @param arg
     * @param session
     * @param request
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/clearCombine/{no}", method = RequestMethod.GET)
    public BaseResult clearCombine(PurchaseOrderBill arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        Object list_order = service.clearCombine(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        log("清零", request, arg.getId());
        return new BaseResult(true, "", 200);
    }

    /***
     *
     * @deprecated 三期上线废弃
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public BaseResult delete(PurchaseOrderBill arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        boolean flag = false;
        List<Permission> list = user.getPermissions();
        for (int i = 0; i < list.size(); i++) {
            Permission p = list.get(i);
            if (p.getId() == 137) {
                flag = true;
            }
        }
        Object list_order = service.delete(arg, flag);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        return new BaseResult(true, list_order.toString(), 200);
    }

    /***
     * 删除合并发货
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/deleteCombine/{no}", method = RequestMethod.GET)
    public BaseResult deleteCombine(PurchaseOrderBill arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        arg.setCreateId(String.valueOf(user.getId()));
        boolean flag = iPermissionService.hasPermission(user.getId(), 137, user.getPermissions());
        Object list_order = service.deleteCombine(arg, flag);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        }
        return new BaseResult(true, "", 200);
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(PurchaseOrderBill arg, HttpServletRequest request) {
        PurchaseOrderBill purchase = service.selectByPrimaryKey(arg.getId());
        int list_order = service.updateByPrimaryKeySelective(arg);
        if (list_order > 0) {
            Map<String, Object> res = CompareObject.contrastObj(arg, purchase);
            log(res, request, arg.getId());
        }
        return new BaseResult(true, list_order);
    }


    /**
     * u 入库
     *
     * @param arg
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/instore", method = RequestMethod.POST)
    public BaseResult instore(PurchaseOrderBill arg, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constants.USER);
        arg.setReceiverId(String.valueOf(user.getId())); // receiver user
        if (arg.getNumberReceive().equals(BigDecimal.valueOf(0.0))) {
            return new BaseResult(false, "入库数量不能为0!", 403);
        }
        Object list_order = service.instore(arg);
        if (list_order instanceof String) {
            return new BaseResult(true, list_order);
        } else {
            log("入库，" + arg.getNumberReceive(), request, arg.getId());
        }
        return new BaseResult(true, list_order);
    }

    /**
     * 批量入库
     *
     * @param arg
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/instoreCombine", method = RequestMethod.POST)
    public BaseResult instoreCombine(PurchaseOrderBillVo arg, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constants.USER);
        arg.setReceiverId(String.valueOf(user.getId())); // receiver user
        Object list_order = service.instoreCombine(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order.toString(), 403);
        } else {
            log("入库，" + arg.getNumbers(), request, arg.getId());
        }
        return new BaseResult(true, list_order);
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult delete(PurchaseOrderBill arg, HttpServletRequest request) {
        int list_order = service.deleteByPrimaryKey(arg.getId());
        BaseResult res = new BaseResult(true, list_order);
        if (list_order > 0) {
            log("删除", request, arg.getId());
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/allow", method = RequestMethod.POST)
    public BaseResult allow(PurchaseOrderBill arg, HttpServletRequest request) {
        PurchaseOrderBill po = new PurchaseOrderBill();
        po.setNo(arg.getNo());
        po.setCheckStatus("1");
        po.setReason(arg.getReason());
        po.setStatus("1"); // 订单执行中
        int list_order = mapper.updateByNoSelective(po);
        if (list_order > 0) {
            log("审核通过", request, arg.getId());
        }

        return new BaseResult(true, list_order);
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/refuse", method = RequestMethod.POST)
    public BaseResult refuse(PurchaseOrderBillVo arg, HttpServletRequest request) {
        Object list_order = service.refuse(arg);
        if (list_order instanceof String) {
            return new BaseResult(false, list_order);
        } else {
            log("审核拒绝：" + arg.getReason(), request, arg.getId());

        }
        return new BaseResult(true, list_order);
    }

    /**
     * 申请发票
     * v3: 由id申请变为no申请 @date :
     *
     * @param arg
     * @param request
     * @return
     */
    @Transactional
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/applyPaper", method = RequestMethod.GET)
    public BaseResult applyPaper(PurchaseOrderBillVo arg, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constants.USER);
        arg.setPaperApplier(user.getId());
        Object res = service.applyPaper(arg);
        if (!(res instanceof String)) {
            log("申请发票", request, (int) res);
            return new BaseResult(true, "", 200);
        }
        return new BaseResult(false, String.valueOf(res), 403);
    }


    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/save-paper", method = RequestMethod.POST)
    public BaseResult savePaper(OrderPaper op, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        op.setOrderType("3"); // 提货单
        OrderPaper op_res = orderPaperMapper.selectByOrderIdAndOrderType(op);
        int res = 0;
        if (op_res == null) {
            op.setUserId(String.valueOf(user.getId()));
            log("上传提货单", request, Integer.valueOf(op.getOrderId()));
            res = orderPaperService.insertSelective(op);
        } else {
            op.setId(op_res.getId());
            if (op.getPath() != null) {
                log("上传提货单", request, Integer.valueOf(op.getOrderId()));
                op.setPath(op.getPath() + ',' + op_res.getPath());
            }
            ;
            res = orderPaperService.updateByPrimaryKeySelective(op);
        }
        return new BaseResult(true, res);
    }

    /**
     * 导出采购收货单功能
     *
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @RequestMapping(value = "/exportWithAuth", method = RequestMethod.GET)
    public OutputStream export(PurchaseOrderBillVo arg, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {
        ListResult lr = queryWithAuth(arg, session, true);
        List<PurchaseOrderBillVo> list = (List<PurchaseOrderBillVo>) lr.getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "采购收货单Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "采购收货单"; // sheet 名称
        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new HashMap();
            PurchaseOrderBillVo ov = list.get(i);
            map.put("收货单号", ov.getNo());
            map.put("产品名称", ov.getGoodsName());
            map.put("品质规格", ov.getQuality());
            map.put("收货数量", ov.getNumber());
            map.put("单价", ov.getPrice());
            map.put("实收", ov.getNumberReceive());
            map.put("发货中数量", ov.getNumberSending());
            map.put("已发货数量", ov.getNumberSended());
            map.put("审核状态", "0".equals(ov.getCheckStatus()) ? "未审核" : ("1".equals(ov.getCheckStatus()) ? "通过" : ("未通过：" + ov.getReason())));
            String status = "";
            if ("1".equals(ov.getType()) && ov.getNumberReceive().compareTo(BigDecimal.valueOf(0.0)) == 1) {
                status = "执行完成";
            } else if (ov.getStatus().equals("0")) {
                status = "未执行";
            } else if (ov.getStatus().equals("1")) {
                status = "执行中";
            } else if (ov.getStatus().equals("2")) {
                status = "执行完毕";
            }
            map.put("收货单状态", status);
            map.put("发票申请状态", "0".equals(ov.getPaperStatus()) ? "未申请" : ("1".equals(ov.getPaperStatus()) ? "申请中" : ("2".equals(ov.getPaperStatus()) ? "已申请" : "")));
            map.put("供应商", ov.getClienteleName());
            map.put("批号", ov.getBatchNum());
            map.put("收货类型", "0".equals(ov.getType()) ? "车号" : ("1".equals(ov.getType()) ? "介绍信" : "转货权"));
            map.put("车号/收货公司", ov.getCom());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            map.put("免费仓储时间", sdf.format(ov.getStoreTime()));
            map.put("开单用户", ov.getCreateId());
            map.put("开单时间", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ov.getCreateAt()));
            map.put("税率", ov.getTaxRatio());
            BigDecimal total = ov.getPrice().multiply(ov.getNumber());
            BigDecimal taxTotal = Utils.taxTotal(ov.getTaxRatio(), total);
            map.put("不含税金额", total.subtract(taxTotal));
            map.put("税额", taxTotal);
            map.put("价税合计金额", total);
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }
}